package Array;

import java.util.Arrays;

public class MergeArray {
    public static void main(String[] args) {
        int[] a1 = new int[] {1,5,6,2,4,10,11};
        int[] a2 = new int[a1.length];
        iterate(a1,0,2,3,6,a2,0);
        System.out.println(Arrays.toString(a2));
/*        merge(a1,0,2,3,a1.length - 1,a2,0);
        System.out.println(Arrays.toString(a1));
        System.out.println(Arrays.toString(a2));
        System.out.println("======================");*/

    }

    //将数组内两个区间内的有序数组合并-使用递归来实现
    public static void merge(int[] a1, int i, int iEnd, int j , int jEnd,
                             int[] a2, int k) {

        if (i > iEnd) {
            System.arraycopy(a1,j,a2,k,jEnd - j + 1);
             return;
        }
        if (j > jEnd) {
            System.arraycopy(a1,i,a2,k,iEnd - i + 1);
            return;
        }

        if (a1[i] < a1[j]) {
            a2[k] = a1[i];
            merge(a1,i+1,iEnd,j,jEnd,a2,k+1);
        }else if (a1[i] > a1[j]){
            a2[k] = a1[j];
            merge(a1,i,iEnd,j+1,jEnd,a2,k+1);
        }

    }

    //将数组内两个区间内的有序数组合并-使用迭代来实现
    public static void iterate(int[] a1, int i, int iEnd, int j, int jEnd ,int[] a2, int k) {
        while (i <= iEnd && j <= jEnd) {
            if (a1[i] < a1[j]) {
                a2[k] = a1[i];
                i++;
            }else {
                a2[k] = a1[j];
                j++;
            }
            k++;
        }

        if (i > iEnd) {
            System.arraycopy(a1,j,a2,k,jEnd - j + 1);
        } else if (j > jEnd) {
            System.arraycopy(a1,i,a2,k,iEnd - i + 1);
        }
    }

}
